package com.ddxcloud.movie.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddxcloud.movie.dto.WxLoginDTO;
import com.ddxcloud.movie.entity.User;
import com.ddxcloud.movie.mapper.UserMapper;
import com.ddxcloud.movie.service.UserService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    WxMaService wxMaService;

    @Override
    public User getUserByMobile(String mobile) {
        User user = new User();
        Integer isExist = this.baseMapper.isExistUserByUsername(mobile);
        if (isExist != null) {
            user = this.baseMapper.getByUsernameUser(mobile);
        } else {
            user.setUsername(mobile);
            this.baseMapper.insert(user);
        }
        return user;
    }

    @Override
    public User loginByWechat(WxLoginDTO dto) throws WxErrorException {
        WxMaJscode2SessionResult sessionResult = wxMaService.jsCode2SessionInfo(dto.getCode());
        WxMaPhoneNumberInfo phoneInfo = wxMaService.getUserService().getPhoneNoInfo(sessionResult.getSessionKey(), dto.getEncryptedData(), dto.getIv());
        Integer isExist = baseMapper.isExistUserByUsername(phoneInfo.getPurePhoneNumber());
        User user = new User();
        if (isExist == null) {
            user.setUsername(phoneInfo.getPhoneNumber());
            user.setWxOpenId(sessionResult.getOpenid());
            baseMapper.insert(user);
        } else {
            user = this.getUserByMobile(phoneInfo.getPhoneNumber());
        }
        return user;
    }
}
